package com.cf.game.im;

import com.cf.game.im.handler.Handler;
import com.cf.game.msg.PathConstant;
import com.cf.game.node.Node;
import com.cf.game.node.NodeService;
import com.cf.game.node.Pressure;
import com.cf.game.vertx.DeployWorkerVerticle;
import com.cf.util.ObjectJsonUtil;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * boot-awm-WSGate
 * <p>
 * web-socket 接口
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/27 上午 10:25
 */
@Slf4j
@DeployWorkerVerticle
public class ChatVerticle extends AbstractVerticle implements InitializingBean {

    private String listenQueue = "";

    @Autowired
    private NodeService nodeService;

    @Autowired
    private List<Handler> handlers;

    private Map<String, Handler> handlerMap=new HashMap<>();

    @Override
    public void start() throws Exception {
        createMetaTree();
        configEventBus();
    }

    private void configEventBus() {
        EventBus ebs = vertx.eventBus();
        log.info("开始监听事件总线【{}】", listenQueue);
        ebs.consumer(listenQueue, message -> {
            String body = String.valueOf(message.body());

            log.info("收到聊天消息【{}】", body);
            Map dataMap = ObjectJsonUtil.toObject(body, Map.class);
            if (dataMap == null)
                return;

            Handler handler = handlerMap.get(dataMap.get("type"));
            if (handler != null) {
                handler.handle(dataMap, ebs);
            } else {
                log.warn("消息未找到对应的handler");
            }
        });
    }


    private void createMetaTree() {
        listenQueue = nodeService.registerNode(Node.instance(PathConstant.TAIK_NAME, PathConstant.TAIK_PARENT_PATH), Pressure.instance(10));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        handlers.forEach(handler -> {
            handlerMap.putIfAbsent(handler.getSupport(), handler);
        });
    }
}
